package com.asktgapp.user.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;

import com.asktgapp.R;
import com.asktgapp.hxsg.BiuEaseHelper;
import com.asktgapp.hxsg.EaseChatFragment;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.umeng.analytics.MobclickAgent;


/**
 * time:2017/11/22
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class ChatActivity extends AppCompatActivity {
    private EaseChatFragment chatFragment;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_chat);
        chatFragment = new EaseChatFragment();
        chatFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.chat_layout_container, chatFragment).commit();
        EMClient.getInstance().addConnectionListener(connectionListener);
        //检查权限
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
//            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
//                    Manifest.permission.RECORD_AUDIO)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

//            } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.RECORD_AUDIO}, 100);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
//            }
        }

        /**
         * 自己添加的发送消息监听回调
         */
        chatFragment.setOnSendMessageListener(new EaseChatFragment.OnSendMessageListener() {
            @Override
            public void onSendTextMessage(String content) {

            }

            @Override
            public void onSendVoiceMessage(String content) {

            }

            @Override
            public void onSendPicMessage(String content) {

            }

            @Override
            public void onSendBigEmoj(String content) {

            }
        });
    }


//
//    public void upChatMsgToo(final String msg) {
//
//        Apiservice apiservice = ApiUtils.getApiservice();
//        HashMap params = new HashMap();
//        params.put("token", PreferencesUtil.getString(ChatActivity.this, PreferencesUtil.KEY_TOKEN));
//        params.put("toUserId", PreferencesUtil.getInt(ChatActivity.this, PreferencesUtil.USER_ID));
//        params.put("content", msg);
//        params.put("userId", getIntent().getStringExtra("toUserId"));
//        Call<ApiResponseBody> call = apiservice.createChat(params);
//        call.enqueue(new Callback<ApiResponseBody>() {
//            @Override
//            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
//                if (response.isSuccessful()) {
//                    Log.i("hxmsgUp", "重新上传成功！" + msg);
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
//                Log.i("hxmsgUp", "上传失败！" + msg);
//            }
//        });
//    }

    private void signIn(String name, String passwrod) {
        EMClient.getInstance().login(name, passwrod, new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.i("环信", "登录聊天服务器成功！");
            }

            @Override
            public void onError(int i, String s) {
                Log.i("环信", "登录失败！");
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });

    }

    public void reset() {

        if (!EMClient.getInstance().isLoggedInBefore()) {
            signIn(PreferencesUtil.getString(ChatActivity.this, PreferencesUtil.KEY_HX_ID), "123456");
            return;
        }
        EMClient.getInstance().logout(true, new EMCallBack() {

            @Override
            public void onSuccess() {
                signIn(PreferencesUtil.getString(ChatActivity.this, PreferencesUtil.KEY_HX_ID), "123456");
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }


    EMConnectionListener connectionListener = new EMConnectionListener() {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    doDisconnected(error);
                }
            });


        }
    };

    public void doDisconnected(int error) {

//        doLoginOut();
        if (error == EMError.USER_REMOVED) {
//            FMTools.clearUserAccount(ChatActivity.this);
//				onUserException(Constant.ACCOUNT_REMOVED);
            // 显示帐号已经被移除
//            Toast.makeText(this, "帐号已经被移除", Toast.LENGTH_SHORT).show();
            finish();

        } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
            PreferencesUtil.putString(ChatActivity.this, PreferencesUtil.USER_ID, "");
            PreferencesUtil.putString(ChatActivity.this, PreferencesUtil.KEY_HX_ID, "");
            BiuEaseHelper.loginOut();
//            FMTools.clearUserAccount(ChatActivity.this);
//				onUserException(Constant.ACCOUNT_CONFLICT);
            // 显示帐号在其他设备登录
//            showUnLoginSnackbar("帐号在其他设备登录");
//            Toast.makeText(this, "帐号在其他设备登录", Toast.LENGTH_SHORT).show();
//            BiuEaseHelper.reset();
//            finish();

        } else if (error == EMError.SERVER_SERVICE_RESTRICTED) {
//            FMTools.clearUserAccount(ChatActivity.this);
//				onUserException(Constant.ACCOUNT_FORBIDDEN);
            // 显示帐号已经被移除 用户被禁
//            showUnLoginSnackbar("帐号已经被禁");
//            Toast.makeText(this, "帐号已经被禁", Toast.LENGTH_SHORT).show();
//            finish();
        } else {
//            showUnLoginSnackbar("登陆信息已失效，请重新登陆");
//            if (Utils.isForeground(this, this.getLocalClassName()))
//            if (Utils.isForeground(this, this.getComponentName().getClassName()))
//                Toast.makeText(this, "正在重连聊天服务器...", Toast.LENGTH_SHORT).show();
            Log.i("asktg", "正在重连聊天服务器...");
            BiuEaseHelper.reset();
//            finish();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
//        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        String content = chatFragment.messageResult;
        if (!Util.isEmpty(content)) {
//            upChatMsg(content);
        }
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if(!PreferencesUtil.getBoolean(this, PreferencesUtil.KEY_IS_ENGINEER)){
//                finish();
//                Intent intent = new Intent(this, MainActivity.class);
//                intent.putExtra("flag", 123);
//                startActivity(intent);
//                return true;
//            }
//        }

        return super.onKeyDown(keyCode, event);
    }

}
